﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;

namespace HCMServices.GUI
{
    public partial class UpdatePage : PhoneApplicationPage
    {
        WebClient webClient;
        public UpdatePage()
        {
            InitializeComponent();
            btnDownload.Visibility = Visibility.Visible;
            btnCancel.Visibility = Visibility.Collapsed;
        }

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            webClient = new WebClient();
            try
            {
                webClient.OpenReadAsync(new Uri("http://dl.dropbox.com/u/74841729/Database.sdf"), UriKind.Absolute);
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
                webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
            }
            catch (WebException ex)
            {
                throw ex;
            }
            btnDownload.Visibility = Visibility.Collapsed;
            btnCancel.Visibility = Visibility.Visible;
            textBlock3.Visibility = Visibility.Visible;
        }

        void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                if (progressDownload.Value <= progressDownload.Maximum)
                {
                    progressDownload.Value = (double)e.ProgressPercentage;
                    currentByte.Text = e.BytesReceived.ToString() + "B";
                    totalByte.Text = e.TotalBytesToReceive.ToString() + "B";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Cancelled == true)
                return;
            try
            {
                if (e.Result != null)
                {
                    #region Isolated Storage Copy Code
                    IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

                    bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);

                    string DBFile = "Database.sdf";
                    IsolatedStorageFileStream isolatedStorageFileStream = new IsolatedStorageFileStream(DBFile, FileMode.Create, isolatedStorageFile);
                    long DBSize = (long)e.Result.Length;
                    byte[] byteRecord = new byte[DBSize];
                    e.Result.Read(byteRecord, 0, byteRecord.Length);
                    isolatedStorageFileStream.Write(byteRecord, 0, byteRecord.Length);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            Finish();
            MessageBox.Show("Update Sucessfull!");
        }

        protected bool IncreaseIsolatedStorageSpace(long quotaSizeDemand)
        {
            bool CanSizeIncrease = false;
            IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
            //Get the Available space
            long maxAvailableSpace = isolatedStorageFile.AvailableFreeSpace;
            if (quotaSizeDemand > maxAvailableSpace)
            {
                if (!isolatedStorageFile.IncreaseQuotaTo(isolatedStorageFile.Quota + quotaSizeDemand))
                {
                    CanSizeIncrease = false;
                    return CanSizeIncrease;
                }
                CanSizeIncrease = true;
                return CanSizeIncrease;
            }
            return CanSizeIncrease;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (webClient != null && webClient.IsBusy)
            {
                webClient.CancelAsync();
                Finish();
            }
        }

        private void Finish()
        {
            webClient = null;
            progressDownload.Value = 0;
            btnCancel.Visibility = Visibility.Collapsed;
            btnDownload.Visibility = Visibility.Visible;
            currentByte.Text = "0B";
            totalByte.Text = "0B";
        }

        private void btnHome_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/GUI/MainPage.xaml", UriKind.Relative));
        }
    }
}